package org.enate.bloatterrorist;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;

import net.margaritov.preference.colorpicker.ColorPickerDialog;
import net.margaritov.preference.colorpicker.ColorPickerDialog.OnColorChangedListener;

import org.enate.bloatterrorist.AppListFragment.PInfo;
import org.xmlpull.v1.XmlPullParser;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public final class API {
	private static final String TAG = "API";
	private static int API_Level = 0;
	protected static final int APPENABLECMD = 1;
	protected static final int APPDISABLECMD = 2;
	protected static ActivityInfo[] arr_ai = null;
	private static int j=0, k=0;
	private static Intent i = null;
	private static File f;
	private static boolean isFound = false;

	protected static Animation a1, a2;
	protected static AnimationListener al1, al2;
	
	protected static final int int_action_title = 		0;
	protected static final int int_action_launch = 		1;
	protected static final int int_action_freeze = 		2;
	protected static final int int_action_defrost = 	3;
	protected static final int int_action_manage = 		4;
	protected static final int int_action_buildevent =	5;
	protected static final int int_action_buildfilter = 6;
	
	protected static final int int_action_pref_gvi_pressaction_launch = 0;
	protected static final int int_action_pref_gvi_pressaction_showqa = 1;
	
	//-------------------------------------------- >>
	protected static final String str_prefSearchHistory = "pref_searchHistory";
	protected static final String str_pref_gvi_pressaction = "pref_gvi_pressaction";
	protected static final String str_pref_filterpref_ime = "pref_filterpref_ime";
	protected static final String str_pref_backgroundColor = "pref_backgroundColor";
	protected static final String str_pref_gv_numCols = "pref_gv_numCols";
	//-------------------------------------------- <<
		
	private static String mLauncherActivityClassName;
	protected static AssetManager mCurAm = null;
	protected static XmlResourceParser xml = null;
	protected static Resources mCurResources = null;
	
	protected static ColorPickerDialog cpd;
	
	
	
	
	
	
	
	
	
	
	protected static int getOrientation(){
		return Main.c.getResources().getConfiguration().orientation;
	}
	
	
	
	
	
	
	//-----------------------------------------------	
	protected static final String getLaunchActivityByPnameViaManifest(String pname) {
		mLauncherActivityClassName = "";
		boolean isInActivityStanza = false;
		boolean hasFoundLauncherActivity = false;
		try {
			mCurAm = Main.m.createPackageContext(pname, 0).getAssets();
			mCurResources = new Resources(mCurAm, Main.m.getResources().getDisplayMetrics(), null);
			xml = mCurAm.openXmlResourceParser("AndroidManifest.xml");
			int eventType = xml.getEventType();		
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if(hasFoundLauncherActivity) {break;}
				switch(eventType) {
				case XmlPullParser.START_TAG:
					if(xml.getName().equals("activity")) {
						isInActivityStanza = true;
						mLauncherActivityClassName = "";
						for (int i=0; i<xml.getAttributeCount(); i++) {
							if(xml.getAttributeName(i).equals("name")) {
								mLauncherActivityClassName = resolveValue(xml.getAttributeValue(i), mCurResources);
								if(!mLauncherActivityClassName.startsWith(".")) {mLauncherActivityClassName = "."+mLauncherActivityClassName;}
								break;
							}
						}
					}
					else if(xml.getName().equals("category")) {
						for (int i=0; i<xml.getAttributeCount(); i++) {
							if(
								(resolveValue(xml.getAttributeValue(i), mCurResources).equals(Intent.CATEGORY_INFO) || 
								 resolveValue(xml.getAttributeValue(i), mCurResources).equals(Intent.CATEGORY_LAUNCHER)) &&
								 isInActivityStanza){
								hasFoundLauncherActivity = true; break;
							}
						}
					}
					break;
				case XmlPullParser.END_TAG:
					if (isInActivityStanza && xml.getName().equals("activity")) {isInActivityStanza = false;}
					break;
				}
				eventType = xml.nextToken();
			}
		} catch (Exception e){}
		return mLauncherActivityClassName;
	}

	private static final String resolveValue(String in, Resources r) {
		if (null!=in && in.startsWith("@") && null!=r) {
			try {return r.getString(Integer.parseInt(in.substring(1)));} 
			catch (Exception e){}
		}
		return in;
	}
	
	protected static final String getLauncherActivityName(String pname) {
		String LaunchActivity = Main.prefs.getString(pname+"_launchActivity", "");
		if(LaunchActivity.equals("")) {
			try{LaunchActivity = Main.pm.getLaunchIntentForPackage(pname).getComponent().getShortClassName();}
			catch(Exception e) {LaunchActivity = "";}
			if(null==LaunchActivity||LaunchActivity.equals("")){
				try {LaunchActivity = getLaunchActivityByPnameViaManifest(pname);} 
				catch (Exception e) {e.printStackTrace();}
			}
		}
		if(null==LaunchActivity) {return "";}
		if(!LaunchActivity.equals("")) {Main.prefs_editor.putString(pname+"_launchActivity", LaunchActivity).commit();}
		return LaunchActivity;
	}
	
	protected static final Intent getLaunchIntentByPname(String pname) {
		i = null;
		if(pname.equals("com.android.providers.applications")) {return null;}
		String LaunchActivity = Main.prefs.getString(pname+"_launchActivity", "");
		if(LaunchActivity.equals("")) {
			try {LaunchActivity = getLauncherActivityName(pname);}
			catch (Exception e) {e.printStackTrace();}
		}
		if(!LaunchActivity.equals("")) {
			i = new Intent()
				.addCategory(Intent.CATEGORY_LAUNCHER)
				.setAction(Intent.ACTION_MAIN)
				.setComponent(new ComponentName(pname,pname+LaunchActivity))
				.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}
		return i;
	}		
	
	protected static final ActivityInfo[] getActivitiesByPname(String pname) {
		arr_ai = null;
		try {
	        PackageInfo ar = Main.pm.getPackageInfo(pname, PackageManager.GET_ACTIVITIES);
        	if(null!=ar) {
        		if(null!=ar.activities) {
        			if(0 < ar.activities.length) {
        				arr_ai = new ActivityInfo[ar.activities.length];
       					arr_ai = ar.activities;
        			}
        		}
        	}
        }catch(Exception e){}
		return arr_ai;
	}

	protected static final boolean boolApplicationEnabled(String pname) {
		return 
			(Main.pm.getApplicationEnabledSetting(pname)!=PackageManager.COMPONENT_ENABLED_STATE_DISABLED) &&  
			(Main.pm.getComponentEnabledSetting(new ComponentName(pname,getLauncherActivityName(pname)))!=PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
	}
	
	protected static final boolean appToggle(String method, PInfo pInfo){
		boolean result = true;
		if(doExec(method+pInfo.launchIntent.getComponent().flattenToShortString())) {Log.d(TAG,"appToggle("+pInfo.pname+") ------------ froze ["+pInfo.pname+") main package");}
		else {result = false;}
		if(doExec(method+pInfo.pname)) {Log.d(TAG,"appToggle("+pInfo.pname+") ------------ froze ["+pInfo.pname+") main package");}
		else {result = false;}
		return result;
	}
	
	private static final boolean doExec(String commands) {
		Process process = null;
		DataOutputStream os = null;
		InputStreamReader osRes = null, osErr = null;
		boolean accessGiven = false;
		try { 
			process = Runtime.getRuntime().exec("su");
			os = new DataOutputStream(process.getOutputStream());
			osRes = new InputStreamReader(process.getInputStream());
			osErr = new InputStreamReader(process.getErrorStream());
			BufferedReader reader = new BufferedReader(osRes);
			BufferedReader reader_err = new BufferedReader(osErr);
			os.writeBytes(commands+"\nexit\n");
			os.flush();
			String line = reader.readLine();
			String line_err = reader_err.readLine();
			
			while (null!=line) {line = reader.readLine();}
			while (line_err != null) {
				if(line_err.contains("new state: ")) {accessGiven = true;}
				line_err = reader_err.readLine();
			}
			os.flush();
			process.waitFor();
		} catch(Exception e) {}
		finally {
			try {
				if (null!=os) {os.close();}
				if (null!=osRes) {osRes.close();}
				process.destroy();
			}catch(Exception e) {}
		}
		return accessGiven;
	}
	
	protected static final boolean isRooted() {
		isFound = false;
			String[] places = {"/sbin/","/system/bin/","/system/xbin/","/data/local/bin/","/data/local/xbin/","/system/sd/xbin/"};
			for(String where : places) {
				f = new File(where+"su");
				if(f.exists()) {isFound = true;}
			}
		return isFound;
	}
	
	protected static final void launchAppManagerScreen(String pname) {
		String pkgname = "";
		i = new Intent().setFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY);
		API_Level = Build.VERSION.SDK_INT;
		if(API_Level>=9) {i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.fromParts("package", pname, null));}
		else {
			if(API_Level==8) {pkgname = "pkg";}
			else {pkgname = "com.android.settings.ApplicationPkgName";}
			i.setAction(Intent.ACTION_VIEW).setClassName("com.android.settings","com.android.settings.InstalledAppDetails").putExtra(pkgname, pname);
		}
		try {Main.c.startActivity(i);}
		catch(Exception e) {}
	}
	
	protected static final Intent createShirtcut(String[] payload, Drawable dw){
		Intent intent = new Intent();
        //intent.setComponent(new ComponentName());
        i = new Intent();
        //i.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent().setComponent(component));
        i.putExtra(Intent.EXTRA_SHORTCUT_NAME, "testing only");
        if (dw instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) dw;
            i.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap());
        }
        return i;
        //setResult(RESULT_OK, i);
        //finish();
	}


	// Animation effects:
	protected static void homeythewallsaremeltingagain(final View v){
		al1 = new AnimationListener(){
	        @Override public void onAnimationEnd(Animation arg0) {v.startAnimation(a2);}
	        @Override public void onAnimationRepeat(Animation arg0) {}
	        @Override public void onAnimationStart(Animation arg0) {}
	    };
		al2 = new AnimationListener(){
	        @Override public void onAnimationEnd(Animation arg0) {v.startAnimation(a1);}
	        @Override public void onAnimationRepeat(Animation arg0) {}
	        @Override public void onAnimationStart(Animation arg0) {}
	    };
	    
		a1 = new AlphaAnimation(0.3f, 1.0f);
		a1.setDuration(1000);
		a1.setAnimationListener(al1);
		a1.setRepeatMode(Animation.INFINITE);
		
		a2= new AlphaAnimation(1.0f, 0.3f);
		a2.setDuration(1300);
		a2.setAnimationListener(al2);
		a2.setRepeatMode(Animation.INFINITE);
	}	

	protected static View.OnTouchListener otl_HTWAMA(final View v1, final View v2, final boolean repeat) {
		OnTouchListener otl = new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent e) {
				switch(e.getAction()){
				case MotionEvent.ACTION_DOWN:
					v1.setVisibility(View.GONE);
					v1.clearAnimation();
					v2.setVisibility(View.VISIBLE);
					break;
				case MotionEvent.ACTION_UP:
					v2.setVisibility(View.GONE);
					v2.clearAnimation();
					v1.setVisibility(View.VISIBLE);
					if(repeat) {homeythewallsaremeltingagain(v1);}
					v1.startAnimation(API.a1);
					break;
				}
				return false;
			}
			
		};
		return otl;
	}
	
	protected static SeekBar.OnSeekBarChangeListener osbcl() {
		OnSeekBarChangeListener osbcl = new OnSeekBarChangeListener() {
			@Override public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {}
			@Override public void onStartTrackingTouch(SeekBar seekBar) {}
			
			@Override public void onStopTrackingTouch(SeekBar seekBar) {
				PrefsFragment.onSeekBarStateChangedCallback(seekBar);
			}
			
			
		};
		return osbcl;

	}
	
	
	
	protected static void showColorPickerDialog(int rID, final int vID) {
		cpd = new ColorPickerDialog(Main.m, Main.prefs.getInt(API.str_pref_backgroundColor, Color.BLACK));
		cpd.setAlphaSliderVisible(true);
		cpd.setOnColorChangedListener(new OnColorChangedListener() {

			@Override
			public void onColorChanged(int color) {
				switch(vID) {
				case R.id.btn_pref_backgroundColor:
					PrefsFragment.onColorChangedCallback(color);
					break;
				}
			}
			
		});
		cpd.show();
	}
	
	
	
	
	protected static final void checkVurguning() {
		// Made some major changes to prefs from the pre-release. Fix for early testers:
		if (-1 == Main.prefs.getInt("appVersion", -1)) {Main.prefs_editor.clear().commit();}
		try {Main.prefs_editor.putInt("appVersion", Main.pm.getPackageInfo(Main.m.getPackageName(), 0).versionCode).commit();} 
		catch (NameNotFoundException e) {}
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	// SQLite
	
	
	
	
	
	
	
}
